<template>
	<view>
		<view class="countdown">{{ countdown }}</view>
	</view>
</template>

<script>
export default {
	props: {
		time: {
			type: String,
			default: ''
		}
	},
	watch: {
		time: {
			immediate: true, // 立即执行 :当刷新页面时会立即执行一次handler函数
			handler(val) {
				this.endTime = val.replace(/[-.]/g, '/') || '';
				this.calcTime();
			}
		}
	},
	data() {
		return {
			endTime: '',
			countdown: '',
			timer: null
		};
	},
	beforeDestroy() {
		clearInterval(this.timer);
		this.timer = null;
	},
	methods: {
		calcTime() {
			this.timer = setInterval(() => {
				const currentTime = new Date().getTime();
				console.log(currentTime, 'currentTimecurrentTime');
				const endTime = new Date(this.endTime).getTime();
				console.log(endTime, 'endTimeendTime');
				if (endTime < currentTime) {
					this.countdown = '已超时';
					console.log(this.countdown, 'this.countdown');
					clearInterval(this.timer);
					return;
				}
				const countdownTime = (endTime - currentTime) / 1000;
				let hour = Math.floor(countdownTime / (60 * 60));
				let min = Math.floor((countdownTime % (60 * 60)) / 60);
				let second = Math.floor(countdownTime % 60);
				hour = hour < 10 ? '0' + hour : hour;
				min = min < 10 ? '0' + min : min;
				second = second < 10 ? '0' + second : second;

				this.countdown = `${hour}:${min}:${second}`;
			}, 1000);
		}
	}
};
</script>

<style lang="scss" scoped>
.countdown {
	font-size: 24rpx;
	font-weight: 700;
	color: #ed4014;
}
</style>
